﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using DataCollector.Entity;

namespace DataCollector.Dao
{
    public class TestDao
    {
        WriteMonitorDataDao dao = null;
        public void TestMain()
        {
            try
            {
                string fileName = "c:\\te.mdb";
                dao = new WriteMonitorDataDao(fileName);
                dao.Open();
                Timer tRead = new Timer();
                tRead.Interval = 2000;
                tRead.Elapsed += new ElapsedEventHandler(dispatcherTimerRead_Tick);
                tRead.Enabled = true;

                Timer tWrite = new Timer();
                tWrite.Interval = 3000;
                tWrite.Elapsed += new ElapsedEventHandler(dispatcherTimerWrite_Tick);
                tWrite.Enabled = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (dao != null && dao.IsOpen)
                {
                    dao.Close();
                }
                Console.ReadKey();
            }
            finally
            {
               
            }
            Console.ReadKey();
            if (dao != null && dao.IsOpen)
            {
                dao.Close();
            }
        }

        private DBSelectResult lastData = null;
        void dispatcherTimerRead_Tick(object sender, ElapsedEventArgs e)
        {
            if (!dao.IsOpen)
            {
                dao.Open();
            }
            DBSelectResult data = dao.ReadLastData();
            if (data == null)
            {
                return;
            }
            if (lastData == null)
            {
                lastData = data;
                return;
            }
            if (data.Id == lastData.Id)
            {
                return;
            }

            Console.WriteLine(data.ExportTime + ":" + "湿度：" + data.Humidity + " 光照：" + data.Illumination + " 温度：" + data.Temperature);
            lastData = data;
        }

        void dispatcherTimerWrite_Tick(object sender, ElapsedEventArgs e)
        {
            MonitorResult mr = new MonitorResult();
            Random r = new Random();
            mr.Humidity = r.Next(20, 35);
            mr.Temperature = r.Next(20, 35);
            mr.Illumination = r.Next(100, 120);
            if (!dao.IsOpen)
            {
                dao.Open();
            }
            dao.Write(mr);
            //   throw new NotImplementedException();
        }
    }
}
